package com.zx.link.controller;

import com.zx.config.listener.SystemInitBean;
import com.zx.link.entity.Link;
import com.zx.link.entity.LinkType;
import com.zx.link.service.LinkService;
import com.zx.util.HttpImage;
import com.zx.util.LinkToHtml;
import com.zx.util.LinkToTreeGrid;
import com.zx.util.ResponseUtil;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
@RequestMapping("/link")
public class LinkController {

    private final static Logger logger = LoggerFactory.getLogger(LinkController.class);

    @Autowired
    private LinkService linkService;

    /**
     * 1.初始化页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String html(Model model) {
        try {
            List<Link> all = linkService.getAll();
            model.addAttribute("links", all);
            model.addAttribute("types", SystemInitBean.LINK_TYPES);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/link/index";
    }

    /**
     * 2.增加link
     *
     * @param link
     * @param request
     * @return
     */
    @RequestMapping("/insert")
    @ResponseBody
    public String insert(Link link, HttpServletRequest request) {
        try {
            //读取图标
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile iconFile = req.getFile("iconFile");
            if (iconFile.getSize() == 0L) {//没有上传图片
                //抓取网络资源自动添加图标
                byte[] httpIcon = HttpImage.getIconByUrl(link.getUrl());
                if (httpIcon != null && httpIcon.length != 0) {//获得网络资源
                    link.setIcon(httpIcon);
                } else {//获得网络资源失败
                    byte[] img = SystemInitBean.DEFAUTL_IMG_BIN;
                    link.setIcon(img);
                }
            } else {//上传图片
                link.setIcon(iconFile.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }

        try {
            link.setIsRemove(0);
            boolean b = this.linkService.insert(link);
            if (b) {
                return "1";
            } else {
                return "2";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "2";
        }
    }

    /**
     * 3.逻辑删除link
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(Integer id) {
        try {
            Link link = this.linkService.getById(id);
            link.setIsRemove(1);
            boolean b = this.linkService.update(link);
            if (b) {
                return "1";
            } else {
                return "0";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    /**
     * 4.彻底删除link
     *
     * @param id
     * @return
     */
    @RequestMapping("/drop")
    @ResponseBody
    public String drop(Integer id) {
        try {
            boolean b = this.linkService.delete(id);
            if (b) {
                return "1";
            } else {
                return "0";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    /**
     * 5.修改
     *
     * @param link
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(Link link, HttpServletRequest request) {

        try {
            //修改图片
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile iconFile = req.getFile("iconFile");
            if (iconFile.getSize() != 0L) {
                link.setIcon(iconFile.getBytes());
            } else {
                link.setIcon(this.linkService.getIconById(link.getId()));
            }
			/*byte[] httpIcon = HttpImage.getIconByUrl(link.getUrl());
			if(httpIcon == null || httpIcon.length == 0){
				link.setIcon(SystemInitBean.DEFAUTL_IMG_BIN);
			} else {
				link.setIcon(httpIcon);
			}*/
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }

        try {
            boolean b = this.linkService.update(link);
            if (b) {
                return "1";
            } else {
                return "0";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }


    /**
     * 6.查询treegrid
     *
     * @param response
     */
    @RequestMapping("/treegrid")
    @ResponseBody
    public void getAll(HttpServletResponse response) {
        try {
            List<Link> linkList = this.linkService.getAll();
            List<LinkType> types = SystemInitBean.LINK_TYPES;
            //将数据转为treegrid格式的数据
            String json = LinkToTreeGrid.toJson(linkList, types);
            ResponseUtil.write(response, json);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[response 写入数据失败]");
        }
    }

    /**
     * 7.查询一个
     *
     * @param id
     * @return
     */
    @RequestMapping("/getById")
    @ResponseBody
    public Link getById(Integer id) {
        try {
            return this.linkService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 8.查询所有类型
     *
     * @return
     */
    @RequestMapping("/types")
    @ResponseBody
    public List<LinkType> linkType() {
        try {
            return SystemInitBean.LINK_TYPES;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 9.查询图片
     *
     * @param id
     * @param response
     */
    @RequestMapping("/icon/{id}")
    public void getIconById(@PathVariable("id") Integer id, HttpServletResponse response) {
        try {
            byte[] b = linkService.getIconById(id);
            if (b != null) {
                response.getOutputStream().write(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 10.查询回收站
     *
     * @param
     * @param response
     */
    @RequestMapping("/recycle")
    @ResponseBody
    public List<Link> recycle() {
        try {
            List<Link> allDelete = this.linkService.getAllDelete();
            return allDelete;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 11.恢复被删除的
     *
     * @param
     * @param response
     */
    @RequestMapping("/recover")
    @ResponseBody
    public String recover(Integer id) {
        try {
            Link link = this.linkService.getById(id);
            link.setIsRemove(0);
            boolean b = this.linkService.update(link);
            if (b) {
                return "1";
            } else {
                return "0";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    /**
     * 导出书签
     *
     * @param response
     */
    @RequestMapping("/bookmark")
    @ResponseBody()
    public void bookmark(HttpServletResponse response) {
        try {
            List<Link> linkList = this.linkService.getAll();
            List<LinkType> types = SystemInitBean.LINK_TYPES;
            String html = LinkToHtml.toHTML(linkList, types);

            response.setContentType("Content-Type:text/html;charset=UTF-8");
            response.getOutputStream().write(html.getBytes(StandardCharsets.UTF_8));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
